package com.example.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.*;

import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class ServerHandler  extends SimpleChannelInboundHandler<String> {
    /*
    * 建立连接，发送庆祝消息
    * */
    @Override
    public void channelActive(ChannelHandlerContext ctx)throws Exception{
        ctx.write("weclome to "+ InetAddress.getLocalHost().getHostName()+"!\n");
        ctx.write("It is "+new Date()+"!\n");
        ctx.flush();
    }

//业务逻辑处理

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String req) throws Exception {
                String respone;
                boolean close=false;
                if(req.isEmpty()){
                    respone="try agagin\n";
                }else  if("bye".equals(req.toLowerCase())){
                    respone="Have a good day ,my boy \n";
                    close=true;
                }else{
                    respone="did you say "+req+"?\n";
                }
        ChannelFuture write = channelHandlerContext.write(respone);
        if(close==true){
        write.addListener(ChannelFutureListener.CLOSE);
    }
//    假设这里有一个服务器要处理的非常的耗时的一个任务，我们肯定是异步执行的。
//        channelHandlerContext.channel().eventLoop().execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(10*1000);
//                    channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("hello lovae", StandardCharsets.UTF_8));
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        });
    }

    //数据读取完毕的时候
    @Override
    public void channelReadComplete(ChannelHandlerContext context){
context.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }

}
